package com.wds.service.impl;

import com.wds.domain.JsonResult;
import com.wds.domain.entity.LoginUser;
import com.wds.domain.entity.User;
import com.wds.domain.vo.LoginVo;
import com.wds.domain.vo.UserInfoVo;
import com.wds.exception.CustomException;
import com.wds.service.BlogLoginService;
import com.wds.common.utils.BeanCopyUtils;
import com.wds.common.utils.JwtUtils;
import com.wds.common.utils.RedisCacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author WDs , wds8.24@outlook.com
 * @version 1.0
 * @since 2022-10-24 15:47
 */
@Service
public class BlogLoginServiceImpl implements BlogLoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCacheUtils redisCache;

    @Override
    public JsonResult<Object> login(User user) {
        // 创建认证对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        // 获取认证信息
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        if (Objects.isNull(authenticate)) {
            throw new CustomException("用户名或者密码错误");
        }
        // 获取UserID 生成 Token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String id = loginUser.getUser().getId().toString();
        String jwtToken = JwtUtils.createJWT(id);
        // 把用户信息存储到redis
        redisCache.setCacheObject("LoginUser:" + id,loginUser);
        // 将token 和 userInfo发送到前端

        return JsonResult.ok(new LoginVo(jwtToken, BeanCopyUtils.copy(loginUser.getUser(), UserInfoVo.class)));
    }

    /**
     * 退出登录
     */
    @Override
    public JsonResult<Object> logout() {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String key = "LoginUser:" + loginUser.getUser().getId();
        redisCache.deleteObject(key);
        return JsonResult.ok("登出成功");
    }
}
